/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* ans = l1;
        int count = 0;
        ListNode* tail = nullptr; // 记录最后一个节点用于连接
        while (l1 && l2) {
            int curSum = l1->val + l2->val + count;
            count = curSum / 10;
            l1->val = curSum % 10;
            tail = l1;
            l1 = l1->next;
            l2 = l2->next;
        }
        if (l2) {
            tail->next = l2;
        }
        ListNode* cur = tail->next;
        while (cur && count) {
            int curSum = cur->val + count;
            count = curSum / 10;
            cur->val = curSum % 10;
            if (!cur->next && count) {
                cur->next = new ListNode(count);
                count = 0;
            }
            cur = cur->next;
        }
        if (count) {
            ListNode* finalTail = ans;
            while (finalTail->next) {
                finalTail = finalTail->next;
            }
            finalTail->next = new ListNode(count);
        }

        return ans;
    }
};
